<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';

import { computed, markRaw, onMounted, ref } from 'vue';

import { AuthenticationLogin, z } from '@vben/common-ui';
import { $t } from '@vben/locales';

import {
  getCaptchaApi
} from '#/api/core/auth'
import { useAuthStore } from '#/store';
import { ImageCaptcha } from '@vben/common-ui';

defineOptions({ name: 'Login' });

const authStore = useAuthStore();

const formSchema = computed((): VbenFormSchema[] => {
  return [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: $t('authentication.usernameTip'),
      },
      fieldName: 'username',
      label: $t('authentication.username'),
      rules: z.string().min(1, { message: $t('authentication.usernameTip') }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: $t('authentication.password'),
      },
      fieldName: 'password',
      label: $t('authentication.password'),
      rules: z.string().min(1, { message: $t('authentication.passwordTip') }),
    },
    {
      component: markRaw(ImageCaptcha),
      componentProps: {
        imageSrc: captchaImg.value,
        placeholder: '请输入验证码',
        refreshText: '点击刷新验证码',
        onRefresh: getCaptcha,
      },
      fieldName: 'verifyCode',
      label: '验证码',
      rules: z.string().min(1, { message: '请输入验证码' }),
    },
  ];
});

// 验证码相关
const captchaId = ref<string>('');
const captchaImg = ref<string>('');

// 获取验证码
async function getCaptcha() {
  try {
    const result = await getCaptchaApi();
    captchaId.value = result.id;
    captchaImg.value = result.img;
  } catch (error) {
    console.error('获取验证码失败:', error);
  }
}

// 处理登录
async function handleLogin(values: any) {
  try {
    await authStore.authLogin('username', {
      ...values,
      captchaId: captchaId.value,
      verifyCode: values.verifyCode,
    });
  } catch (error) {
    // 登录失败后刷新验证码
    await getCaptcha();
  }
}

// 组件挂载时获取验证码
onMounted(() => {
  getCaptcha();
});
</script>

<template>
  <AuthenticationLogin
    :form-schema="formSchema"
    :loading="authStore.loginLoading"
    @submit="handleLogin"
  />
</template>
